package com.example.demo.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONString;
import cn.hutool.json.JSONUtil;
import com.example.demo.po.user.User;
import com.example.demo.vo.ResultVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//spring拦截器，需要配置mvcConfig
public class LoginInterceptor implements HandlerInterceptor {

    //这里不能使用自动依赖注入，因为LoginInterceptor是在mvcConfig里手动new出来的，没有被spring管理
    //所以让mvcConfig通过参数传入
    private StringRedisTemplate stringRedisTemplate;


    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中token
        String token = request.getHeader("authorization");
        //2。基于token获得redis中的用户
        if (StrUtil.isBlank(token)) {
            response.setStatus(200);
            response.setCharacterEncoding("utf-8");
            PrintWriter pw = response.getWriter();
            pw.write(JSONUtil.toJsonStr(new ResultVO<>(-5,"未登录")));
            return false;
        }
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(Constant.LOGIN_USER_KEY + token);
        if(entries.isEmpty()){
//            response.setStatus(401);
            response.setStatus(200);
            response.setCharacterEncoding("utf-8");
            PrintWriter pw = response.getWriter();
            pw.write(JSONUtil.toJsonStr(new ResultVO<>(-5,"未登录")));
            return false;
        }
        //3.将查询到的map转为user
        User user= BeanUtil.fillBeanWithMap(entries, new User(), false);

        //4.将信息存到ThreadLocal
        UserHolder.saveUser(user);

        //5.刷新redis中token有效期
        stringRedisTemplate.expire(Constant.LOGIN_USER_KEY + token,Constant.LOGIN_USER_TTL, TimeUnit.SECONDS);

        //6.放行
        return true;

    }
}
